package org.jim.server.command.handler;

import com.alibaba.fastjson.JSONArray;
import org.jim.common.*;
import org.jim.common.cache.redis.RedisCache;
import org.jim.common.cache.redis.RedisCacheManager;
import org.jim.common.packets.*;
import org.jim.common.utils.ImKit;
import org.jim.common.utils.JsonKit;
import org.jim.server.command.AbstractCmdHandler;
import org.tio.core.ChannelContext;

import java.util.List;

/**
 * @author dc
 * @title: HasFriendHandler
 * @projectName nb_chat_core
 * @description: TODO
 * @date 2019/7/1010:15
 */
public class HasFriendHandler extends AbstractCmdHandler {


    @Override
    public Command command() {
        return Command.COMMAND_HASFRIEND_REQ;
    }

    @Override
    public ImPacket handler(ImPacket packet, ChannelContext channelContext) throws Exception {
        HasFriendReqBody hasFriendReqBody = JsonKit.toBean(packet.getBody(), HasFriendReqBody.class);
        ImSessionContext imSessionContext = (ImSessionContext) channelContext.getAttribute();
        Client client = imSessionContext.getClient();
        User user = client.getUser();
        ImPacket respPacket = null;
        if (hasFriendReqBody == null) {
            RespBody chatDataInCorrectRespPacket = new RespBody(Command.COMMAND_HASFRIEND_RESP, ImStatus.C10020);
            respPacket = ImKit.ConvertRespPacket(chatDataInCorrectRespPacket, channelContext);
            respPacket.setStatus(ImStatus.C10020);
        } else {
            HasFriendRespBody body = new HasFriendRespBody(Command.COMMAND_HASFRIEND_RESP, 0, hasFriendReqBody.getFriendId(), "是否存在好友的通知");
            RedisCache UserCache = RedisCacheManager.getCache(ImConst.USER);
            List<User> friendUsers = JSONArray.parseArray(UserCache.get(user.getId() + ":" + ImConst.FRIENDS).toString(), Group.class).get(0).getUsers();
            for (User user1 : friendUsers) {
                if (user1.getId().equals(hasFriendReqBody.getFriendId())) {
                    body.setHasFriendType(1);
                    break;
                }
            }
            respPacket = ImKit.ConvertRespPacket(body, channelContext);
        }
        return respPacket;
    }
}
